var $serverurl = '';//http://demo.tonair.com.tw/htdocs/index.php';
$(document).ready(function() {
    /**
    * Global variables
    */
    var completed = 0,
        imgHeight = 9689,
        posArr = [],
        win = [];

    for (var i=1;i<=50;i++) { 
        posArr[i] = i*193;
        win[i*193] = i;
    }

    /**
    * @class Slot
    * @constructor
    */
    function Slot(el, max, step) {
        this.speed = 0; //speed of the slot at any point of time
        this.step = step; //speed will increase at this rate
        this.si = null; //holds setInterval object for the given slot
        this.el = el; //dom element of the slot
        this.maxSpeed = max; //max speed this slot can have
        this.pos = null; //final position of the slot    

        $(el).pan({
            fps:30,
            dir:'down'
        });
        $(el).spStop();
    }

    /**
    * @method start
    * Starts a slot
    */
    Slot.prototype.start = function() {
        var _this = this;
        $(_this.el).addClass('motion');
        $(_this.el).spStart();
        _this.si = window.setInterval(function() {
            if(_this.speed < _this.maxSpeed) {
                _this.speed += _this.step;
                $(_this.el).spSpeed(_this.speed);
            }
        }, 100);
    };

    /**
    * @method stop
    * Stops a slot
    */
    Slot.prototype.stop = function(arg) {
        var _this = this,
            limit = 3;
        clearInterval(_this.si);
        _this.si = window.setInterval(function() {
            if(_this.speed > limit) {
                _this.speed -= _this.step;
                $(_this.el).spSpeed(_this.speed);
            }
            if(_this.speed <= limit) {
                //_this.finalPos(_this.el);
                _this.finalPos(arg);
                $(_this.el).spSpeed(0);
                $(_this.el).spStop();
                clearInterval(_this.si);
                $(_this.el).removeClass('motion');
                _this.speed = 0;
            }
            //$("#aslot").get(0).play();
        }, 100);

    };

    /**
    * @method finalPos
    * Finds the final position of the slot
    */
    Slot.prototype.finalPos = function(arg) {
        var el = this.el,
            el_id,
            pos,
            posMin = 2000000000,
            best,
            bgPos,
            i,
            j,
            k,
            dura;
        el_id = $(el).attr('id');
        //pos = $(el).css('background-position'); //for some unknown reason, this does not work in IE
        pos = document.getElementById(el_id).style.backgroundPosition;
        pos = pos.split(' ')[1];
        pos = parseInt(pos, 10);

        for(i = 1; i < posArr.length; i++) {
            for(j = 0;;j++) {
                k = posArr[i] + (imgHeight * j);
                if(k > pos) {
                    if((k - pos) < posMin) {
                        posMin = k - pos;
                        best = k;
                        this.pos = posArr[i]; //update the final position of the slot
                    }
                    break;
                }
            }
        }
        
        if (typeof(arg) !== "undefined"){
            best = posArr[arg];
            this.pos = posArr[arg];
            
            for(j = 0;;j++) {
                k = best + (imgHeight * j);
                if(k > pos) {
                    best = k;
                    dura = ((k - pos) < 500)? 1000 : 
                           ((k - pos) < 1000)? 2000 :
                           ((k - pos) < 2000)? 4000 :
                           ((k - pos) < 3000)? 6000 :
                           ((k - pos) < 4000)? 8000 : 10000;
                    break;
                }
            }
            console.log(best);
            
        }
        
        //best += imgHeight + 4;
        bgPos = "0 " + best + "px";
        $(el).animate({
            backgroundPosition:"(" + bgPos + ")"
        }, {
            duration: dura,
            complete: function() {
                completed ++;
                $("#aslot").get(0).play();
            }
        });
    };
    
    /**
    * @method reset
    * Reset a slot to initial state
    */
    Slot.prototype.reset = function() {
        var el_id = $(this.el).attr('id');
        $._spritely.instances[el_id].t = 0;
        var p = (el_id == 'slot1')? 804 : 
                (el_id == 'slot2')? 201 :
                (el_id == 'slot3')? 402 : 402;
        $(this.el).css('background-position', '0px '+p+'px');
        this.speed = 0;
        completed = 0;
        $('#result').html('');
    };

    function enableControl() {
        $('#control').attr("disabled", false);
    }

    function disableControl() {
        $('#control').attr("disabled", true);
    }

    function printResult(msgObj) {
        var res;
        if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
            res = "恭喜中獎!(票價皆為未稅價)<br>"+" 中獎檢核碼:"+msgObj.check;
            $("#awin").get(0).play();
            $(".main").css("background-image", "url(images/background-fw.gif)");
        } else {
            res = (msgObj.result === 'empty')? "謝謝您的參與!":"下次會更好!";
            $("#anowin").get(0).play();
        }
        $('#result').html(res);
    }

    //create slot objects
    var a = new Slot('#slot1', 40, 1),
        b = new Slot('#slot2', 20, 2),
        c = new Slot('#slot3', 20, 3);

    /**
    * Slot machine controller
    */
    $('#control').click(function() {
        var x,
            msgObj = null;
        //if(this.innerHTML == "Start") {
        if($(this).data("status") == "Start") {
            a.start();
            b.start();
            c.start();
            //this.innerHTML = "Stop";
            $(this).data("status","Stop");
            $(this).removeClass();
            $(this).addClass('stopBtn');
            $("#aroll").get(0).play();
            disableControl(); //disable control until the slots reach max speed
            
            //check every 100ms if slots have reached max speed 
            //if so, enable the control
            x = window.setInterval(function() {
                if(a.speed >= a.maxSpeed && b.speed >= b.maxSpeed && c.speed >= c.maxSpeed) {
                    enableControl();
                    window.clearInterval(x);
                }
            }, 100);
        //} else if(this.innerHTML == "Stop") {
        } else if($(this).data("status") == "Stop") {
            
            $.ajax({
                url: $serverurl+"/api",
                type: "GET",
                dataType: "json",
                error: function(){
                    alert("連線錯誤，請再試一次！");
                    a.reset();
                    b.reset();
                    c.reset();
                },
                success: function(json) {
                    $("#aslot").get(0).play();
                    $s1 = json.s1;
                    a.stop($s1);
                    $s2 = json.s2;
                    b.stop($s2);
                    $s3 = json.s3;
                    c.stop($s3);
                    msgObj = json;
                }
            });
            /*
            a.stop();
            b.stop();
            c.stop();
            */
            //this.innerHTML = "Reset";
            $(this).data("status","Reset");
            $(this).removeClass();
            $(this).addClass('resetBtn');
            //disableControl(); //disable control until the slots stop
            
            //check every 100ms if slots have stopped
            //if so, enable the control
            x = window.setInterval(function() {
                if(a.speed === 0 && b.speed === 0 && c.speed === 0 && completed === 3) {
                    enableControl();
                    window.clearInterval(x);
                    printResult(msgObj);
                }
            }, 100);
        } else { //reset
            a.reset();
            b.reset();
            c.reset();
            //this.innerHTML = "Start";
            $(this).data("status","Start");
            $(this).removeClass();
            $(this).addClass('startBtn');
            $(".main").css("background-image", "url(images/background.jpg)");
        }
    });
});
